
export function getFieldConfigById(id, formDefinition) {
  if (!id || !formDefinition) return null;
  let fields = formDefinition && formDefinition.fields || [];
  fields = getAllFields(formDefinition, [formDefinition.id])
  let res = fields.find(f => f.id === id);
  if (res) return res;
  let subForms = formDefinition && formDefinition.subForms || [];
  subForms.forEach(subform => {
    fields = subform && subform.fields || [];
    res = res || fields.find(f => f.id === id);
  });
  let views = formDefinition && formDefinition.views || [];
  views.forEach(v => {
    let components = v && v.components || [];
    res = res || components.find(c => c.id === id);
  });
  return res;
}

export function getAllFields(formDefinition, includeForms = undefined) {
  formDefinition = formDefinition || [];
  let res = [], fields = formDefinition.fields || [], subForms = formDefinition.subForms || [], subFormMap = {};
  includeForms = includeForms || undefined;
  if (!includeForms || includeForms.includes(formDefinition.id)) {
    res.push(...fields);
  }
  subForms.forEach(subForm => {
    if (includeForms && !includeForms.includes(subForm.id)) return;
    subFormMap[subForm.id] = subForm;
    fields = subForm.fields || [];
    res.push(...fields);
  });

  function getFormNameById(formId) {
    if (formId === formDefinition.id) return '[主表]';
    return subFormMap[formId] && `[${subFormMap[formId].formName}]` || '';
  }

  // res = res.map(f => ({...f, title: `${getFormNameById(f.formId)} ${f.label}`}));
  res.forEach(f => {
    f.title = `${getFormNameById(f.formId)} ${f.label}`
  })
  res.push(...getDefaultFields(formDefinition));
  return res;
}

function getDefaultFields(formDefinition) {
  let res = [];
  if(!formDefinition.hasFlow) return res;
  res.push({
    id: 'flowStatus',
    fieldName: 'flowStatus',
    searchFieldName: 'flow_status',
    fieldTitleName: 'flowStatusTitle',
    component: 'flowStatus',
    formId: formDefinition.id,
    placeholder: '请选择流程状态',
    label: '流程状态',
    title: '[主表] 流程状态',
  });

  res.push({
    id: 'processInstanceTitle',
    searchFieldName: 'process_instance_title',
    fieldName: 'processInstanceTitle',
    component: 'input',
    formId: formDefinition.id,
    label: '流程标题',
    placeholder: '请输入流程标题',
    title: '[主表] 流程标题',
  });

  return res;
}

export function getSubFormById(id, formDefinition) {
  return (formDefinition && formDefinition.subForms || []).find(subForm => subForm.id === id);
}